import { Command } from '@tauri-apps/plugin-shell'
import { basename, resolve, join, appDataDir } from '@tauri-apps/api/path'
import { copyFile, mkdir, exists } from '@tauri-apps/plugin-fs'

/**
 * 备份项目文件
 * @param {string} projectId 项目ID
 * @param {string} gzPath 压缩包路径
 * @param {number} newVersion 新版本号
 * @returns 
 */
export async function backupProjectFile(projectId, gzPath, newVersion) {
  // 获取应用安装目录
  const dataDir = await appDataDir();
  const backupDir = await join(dataDir, `backup/${projectId}-${newVersion}`);
  // 确保配置目录存在
  const dirExists = await exists(backupDir);
  if (!dirExists) {
    await mkdir(backupDir, { recursive: true });
  }
  // 复制文件到配置目录
  const gzName = await basename(gzPath)
  const targetPath = await join(backupDir, gzName);
  await copyFile(gzPath, targetPath);
  return targetPath;
}

/**
 * 压缩文件夹
 * @param {string} sourceDir 
 * @returns {Promise<{ outPath: string, gzName: string }>}
 */
export async function compressedFolder(sourceDir) {
  const parentDir = await resolve(sourceDir, '../')
  const distDir = await basename(sourceDir)
  const gzName = `${distDir}.tar.gz`
  // 压缩文件夹
  const cmd = new Command('tar', ['-czf', gzName, distDir], {
    cwd: parentDir
  })
  const result = await cmd.execute()
  if (result.code !== 0) {
    throw new Error(result.stderr || '文件压缩失败');
  }
  const outPath = await join(parentDir, gzName)
  return { outPath, gzName, message: result.stderr }
}